package com.googlecode.cswish.util.lucene;

import java.io.IOException;

import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.PayloadAttribute;
import org.apache.lucene.index.Payload;

public class IdPayloadFilter extends TokenFilter {

	private PayloadAttribute payloadAtt;
	private UserIdAttribute idAtt;

	protected IdPayloadFilter(TokenStream input) {
		super(input);
		idAtt = addAttribute(UserIdAttribute.class);
		payloadAtt = addAttribute(PayloadAttribute.class);
	}

	@Override
	public boolean incrementToken() throws IOException {
		if (input.incrementToken()) {
			payloadAtt.setPayload(new Payload(getIdBytes(idAtt.getUserId(), idAtt.getMessageId())));
			return true;
		} else {
			return false;
		}
	}

	public static long getIdValue(byte[] bb, boolean isUserId) {
		if (isUserId) {
			return ((((long) bb[0] & 0xff) << 56)
				     | (((long) bb[1] & 0xff) << 48)
				     | (((long) bb[2] & 0xff) << 40)
				     | (((long) bb[3] & 0xff) << 32)
				     | (((long) bb[4] & 0xff) << 24)
				     | (((long) bb[5] & 0xff) << 16)
				     | (((long) bb[6] & 0xff) << 8) 
				     | (((long) bb[7] & 0xff) << 0));
		} else {
			return ((((long) bb[8] & 0xff) << 56)
				     | (((long) bb[9] & 0xff) << 48)
				     | (((long) bb[10] & 0xff) << 40)
				     | (((long) bb[11] & 0xff) << 32)
				     | (((long) bb[12] & 0xff) << 24)
				     | (((long) bb[13] & 0xff) << 16)
				     | (((long) bb[14] & 0xff) << 8) 
				     | (((long) bb[15] & 0xff) << 0));
		}
	}

	public static byte[] getIdBytes(long userId, long messageId) {
		byte[] writeBuffer = new byte[16];
		writeBuffer[0] = (byte)(userId >>> 56);
        writeBuffer[1] = (byte)(userId >>> 48);
        writeBuffer[2] = (byte)(userId >>> 40);
        writeBuffer[3] = (byte)(userId >>> 32);
        writeBuffer[4] = (byte)(userId >>> 24);
        writeBuffer[5] = (byte)(userId >>> 16);
        writeBuffer[6] = (byte)(userId >>>  8);
        writeBuffer[7] = (byte)(userId >>>  0);
        
        if (messageId != 0) {
	        writeBuffer[8] = (byte)(messageId >>> 56);
	        writeBuffer[9] = (byte)(messageId >>> 48);
	        writeBuffer[10] = (byte)(messageId >>> 40);
	        writeBuffer[11] = (byte)(messageId >>> 32);
	        writeBuffer[12] = (byte)(messageId >>> 24);
	        writeBuffer[13] = (byte)(messageId >>> 16);
	        writeBuffer[14] = (byte)(messageId >>>  8);
	        writeBuffer[15] = (byte)(messageId >>>  0);
        }
		return writeBuffer;
	}
}
